package com.qf.listener;

import com.qf.entity.Order;
import com.qf.feign.api.OrderService;
import com.qf.feign.api.StockService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ShopOrderDeadQueueLIstener {

    @Autowired
    private OrderService orderService;

    @Autowired
    private StockService stockService;

    @RabbitListener(queues = "shop-order-dead-queue")
    public void updateOrderStatus(Order order, Channel channel, Message message) {
        System.out.println(order);

        try {
            // 进入到死信队列后说明订单已经过了1m，1m后订单有可能有那些(已支付，已取消，未支付)
            // 要查询这个订单的最新状态
            Order newOrder = orderService.getOrderById(order.getId());

            // 判断订单的状态
            //    1:未支付，2：已支付，3：已取消，4：已超时，5：已发货
            switch (newOrder.getStatus()) {
                case 1:
                    System.out.println("1m后订单还是未支付，可以把订单的修改成已超时");

                    // 更新订单的状态为已超时
                    orderService.updateOrderStatus(newOrder.getId(), 4);

                    stockService.unlockGoodsStock(newOrder.getId());
                    break;
                case 2:
                    System.out.println("1m后订单已经是支付的状态，不需要处理");
                    break;
                case 3:
                    System.out.println("1m订单的状态是已取消，不需要处理");
                    break;
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
